import tensorflow.compat.v1 as tf
import numpy as np

# random seeds
np.random.seed(777)
tf.set_random_seed(777)

# 基础题
# ①	自定义数据集,随机生成x为10行2列数据，随机赋值y；
x = np.random.uniform(-10., 10., [10, 2])
y = 4. + 3. * x[:, 0] - 5. * x[: , 1] + np.random.normal(size=10)
y = y.reshape(-1, 1)
xy = np.c_[x, y]
xy -= xy.mean(axis=0)
xy /= xy.std(axis=0)

# ②	生成定义符，生成weight，baise.
ph_x = tf.placeholder(tf.float32, [None, 2], name='ph_x')
ph_y = tf.placeholder(tf.float32, [None, 1], name='ph_y')
w = tf.Variable(tf.random.normal([2, 1]), dtype=tf.float32, name='w')
b = tf.Variable(tf.random.normal([1, 1]), dtype=tf.float32, name='b')

# ④	生成模型函数，生成多变量线性损失函数（误差平方和）。
h = tf.matmul(ph_x, w) + b
cost = tf.reduce_mean(tf.square(h - ph_y)) / 2.
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)

# ③	正确创建会话，进行全局初始化.
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    iters = 1000
    group = int(np.ceil(iters / 20))
    print('Training started')
    for i in range(iters):
        _, c = sess.run([train, cost], feed_dict={ph_x: x, ph_y: y})
        if i % group == 0:
            print(f'#{i + 1}: cost = {c}')
    if i % group != 0:
        print(f'#{i + 1}: cost = {c}')
    print('Training over')

    # ⑤	输出预测结果。
    hypo = sess.run(h, feed_dict={ph_x: x})
    print('target, hypothesis:')
    print(np.c_[y, hypo])
